<template>
  <div class="tableFile">
    <div class="file" v-if="files.length">
      <span
        :class="file.path ? 'cp' : ''"
        v-for="(file, index) in files"
        :key="index"
        @click="goHref(file)"
        :title="titleTip(file.path)"
      >
        <svg-icon v-if="file.path" :icon-class="file.type" size="40" />

        <svg-icon v-else icon-class="File-Error" size="40" />
      </span>
    </div>
    <svg-icon v-else icon-class="File-Error" size="40" />
  </div>
</template>

<script>
import axios from "axios"

export default {
  data() {
    return {
      // baseUrl: global.baseurl,
    };
  },
  computed: {
    titleTip(){
      return (path) => {
        if(this.showTitle){
          const pathArr = path.split("/")
          return pathArr[pathArr.length-1]
        }else{
          return "文件"
        }
      }
    }
  },
  methods: {
    goHref(file) {
      const {path,name} = file

      if(!path) throw new Error("必须传入文件下载地址")

      const downFileUrl = this.$GLOBAL.baseurl + "/api/download?path=" + path;

      if(this.changeName) this.changeNameFile(name,downFileUrl,path)

      else this.goURL(downFileUrl)
    },

    changeNameFile(name,downFileUrl,path){
      if(!name) {
        this.goURL(downFileUrl)
        return
      }

      axios.get(this.$GLOBAL.baseurl + "/api/download",{
        params: {
          path
        },
        responseType: 'blob',
      }).then(Blob => {
        const url = URL.createObjectURL(Blob)
        const a = document.createElement("a")
        a.href = url
        a.download = name + /.+(\.\w+)$/.exec(path)[1]
        a.click()
        URL.revokeObjectURL(url)
      })
    },

    goURL(downFileUrl){
      window.location.href = downFileUrl
    }
  },
  props: {
    /**
     * [{
     *  文件类型
     *  type: 'docx' || 'zip',
     *  文件路径
     *  path: ''
     * }]
     *
     */
    files: {
      type: Array,
      default: () => {
        return [];
      },
    },

    showTitle: {
      type: Boolean,
      default: false,
    },

    //修改下载文件名
    changeName: {
      type: Boolean,
      default: false,
    }
  },
};
</script>

<style lang="less" scoped>
.tableFile {
  width: 40px;
  height: 40px;
  .file {
    display: inline-block;
    width: 40px;
    height: 40px;
    display: flex;
    margin-right: 10px;
  }
  .file:last-child {
    margin-right: 0;
  }
}
</style>
